<template>
  <div class="abnormal">
    <div class="flex-header">
        <my-header title="在途取车" />
    </div>
    <div class="content-box">
        <mu-text-field v-model="vin" v-if="isShowVin" placeholder="VIN" ref="vin" class='input' @keyup.enter.native="getConfigData(1)"><i class="iconfont icon-saomiao" @click="scan('vin')"></i></mu-text-field>

        <mu-text-field v-model="toPlace" v-if="isShowSelect" @focus="OpenChs()" placeholder="选择目的地" class='input' readonly="readonly"></mu-text-field>

        <mu-bottom-sheet :open.sync="destination">
            <mu-list @item-click="closeBottomSheet">
                <mu-sub-header>请选择目的地</mu-sub-header>
                <mu-list-item button v-for="(item, index) in options" :key="index" @click="chs(item,index)">
                    <mu-list-item-title>{{item}}</mu-list-item-title>
                </mu-list-item>
            </mu-list>
        </mu-bottom-sheet>
        
        <mu-paper class="paper" v-if="isShowPaper" :z-depth="2">
            <div class="list-content">VIN：<span>{{vin}}</span></div>
            <div class="list-content">车型：<span>{{itemCode}}</span></div>
            <div class="list-content">配置：<span>{{vehicleType}}</span></div>
            <div class="list-content">颜色：<span>{{color}}</span></div>
            <div class="list-content">发运方式：<span>{{transportMode}}</span></div>
            <div class="list-content">仓库：<span>{{warehouse}}</span></div>
            <div class="list-content">路由目的地：<span>{{omDestLocGid}}</span></div>
            <div class="list-content">目的地：<span>{{endPoint}}</span></div>
        </mu-paper>

        <mu-dialog width="320" max-width="60%" :open.sync="openAlert">
            目前不在电子围栏内，是否确认完成?
            <mu-button slot="actions" flat color="primary" @click="closeAlertDialog('y')">确认</mu-button>
            <mu-button slot="actions" flat color="primary" @click="closeAlertDialog('n')">取消</mu-button>
        </mu-dialog>

        <mu-dialog width="320" max-width="60%" :open.sync="openAlertChangeCar">
            确实是否换车?
            <mu-button slot="actions" flat color="primary" @click="closeAlertDialogChangeCar('y')">确认</mu-button>
            <mu-button slot="actions" flat color="primary" @click="closeAlertDialogChangeCar('n')">取消</mu-button>
        </mu-dialog>

        <mu-button color="primary" class="submit" v-if="isShowToPlace" @click='SubmitToPlace' large>确认目的地</mu-button>
        <mu-button color="primary" class="submit" v-if="isShowChangeCar" @click='SubmitChangeCar' large>换车</mu-button>
        <mu-button color="primary" class="submit" v-if="isShowDone" @click='submit' large>确认完成</mu-button>
    </div>
    <scanning v-if="isScanning" :mark="scanMark" v-on:childByValue="childByValue" v-on:closeing="closeing"/>
  </div>
</template>

<script>
import scanning from "@/components/scanning"
import myHeader from "@/components/header"
import api from "@/common/api"
export default {
  components: {
    myHeader, scanning
  },
  data () {
    return {
        overSpeed: 1,
        accuracy: 65,
        isScanning: false,
        scanMark: '',
        destination: false,
        isAction: true,
        openAlertChangeCar: false,
        openAlert: false,
        initSpeeds: '',
        itemCode: '',
        vehicleType: '',
        transportMode: '',
        warehouse: '',
        omDestLocGid: '',
        isShowVin: false,
        isShowSelect: false,
        isShowPaper: false,
        isShowToPlace: false,
        isShowChangeCar: false,
        isShowDone: false,
        openFullscreen: false,
        Loop: null,
        deleteIndex: null, // 删除第几张
        openAlert: false, // 删除图片层
        trajectoryPlan: [],
        text: '', // 备注
        vin: '', // vin
        car: '', // 车型
        endPoint: '',
        color: '', // 颜色
        open1: false, // 底部 类型选择框
        open2: false, // 底部 原因选择框
        abnormalType: "", // 类型 页面显示
        abnormalReas: "", // 原因 页面显示
        abnormalTypeArr: [], // 异常类型
        abnormalReasArrX: [], // 原因选择
        abnormalReasArr: [], // 异常原因
        distence: 5, // 偏移距离
        railRadius: 50, // 取车距离
        workRadius: 50, // 完成距离
        stayTime: 0,
        thePreSPD: 0, // 上一个路段限速
        fromPoint: {
            lng: 0,
            lat: 0
        },
        toPoint: {
            lng: 0,
            lat: 0
        },
        watch: false,
        src: [], // 拍照的图片
        files: [], // 图片文件 base64
        bigImg: null,
        taskId: null,
        FlagStatus: null, // 当前页面状态
        otherTaskTo: false,
        options: [],
        preLeaveTime: 0, // 上次上报偏移时的时间戳
        preSpeedingTime: 0, // 上次上报超速时的时间戳
        isBeginStay: false,
        toPlace: "",
        intervalInitData: null,
        CurrentSection: 0,
        islocked: true
    }
  },
  methods: {
      chs (item, index) {
        this.toPlace = item;
        this.destination = false;
      },
      OpenChs () {
        this.destination = true;
      },
      closeBottomSheet () {
        this.destination = false;
      },
      closeAlertDialogChangeCar (mark) {
        if(mark == 'y'){
            this.SubmitChangeCarSure();
        }
        this.openAlertChangeCar = false;
      },
      SubmitToPlace () {
        let data = Object.assign({}, this.$store.state.user, {
            content: {
                taskId: this.taskId,
                toPlace: this.toPlace
            }
        });
        this.common.reqData(api.app('onroadPlace'), data, res=>{
            console.log(res.data)
            if(res.data.status === 100){
                this.InitWebPage(res.data);
            }else{
                // 提示
                this.Toast({
                    message: res.data.msg
                });
            }
        },err =>{
        });
      },
      SubmitChangeCarSure () {
        let data = Object.assign({}, this.$store.state.user, {
            content: {
                taskId: this.taskId
            }
        });
        this.common.reqData(api.app('onroadChangeCar'), data, res=>{
            console.log(res.data)
            if(res.data.status === 100){
                this.InitWebPage(res.data);
                this.vin = "";
            }else{
                // 提示
                this.Toast({
                    message: res.data.msg
                });
            }
        },err =>{
        });
      },
      SubmitChangeCar () {
        this.openAlertChangeCar = true;
      },
      touchin(index) {
        var _this = this;
        clearInterval(this.Loop); //再次清空定时器，防止重复注册定时器
        this.Loop = setTimeout(function() {
            _this.deleteImgDialog(index);
        }.bind(this), 500);
      },
      cleartime(id,course_id) {
        // 这个方法主要是用来将每次手指移出之后将计时器清零
        clearInterval(this.Loop);
      },
      openFullscreenDialog (index) {
        this.bigImg = this.src[index];
        this.openFullscreen = true;
      },
      closeFullscreenDialog () {
        this.openFullscreen = false;
      },
      closeing (val) {
        val ? this.isScanning = false : null;
      },
      childByValue (val) {
        if(val){
            if(val.split('&')[1] == 'vin'){
                this.vin = val.split('&')[0];
            }
        }
        this.getConfigData(0);
      },
      scan (txt) {
        this.scanMark = txt;
        this.isScanning = true;
      },
      GetVin (way) {
        /* 发送post请求 */
        if(this.islocked){
            this.islocked = false;
            let data = Object.assign({}, this.$store.state.user, {
                content: {
                    vin: this.vin,
                    lat: this.$store.state.latitude,
                    lng: this.$store.state.longitude,
                    way: way
                }
            });
            this.common.reqData(api.app('onroadVin'), data, res=>{
                console.log(res.data)
                if(res.data.status === 100){
                    this.InitWebPage(res.data);
                }else{
                    // 提示
                    this.Toast({
                        message: res.data.msg
                    });
                }
                this.islocked = true;
            },err =>{
                this.islocked = true;
            });
        }
      },
      getConfigData (way) {
        this.GetVin(way);
        // 请求vin数据common.appApi.abnormalVinQuery
        // this.common.distanceCompute({
        //     latitude: this.fromPoint.lat,
        //     longitude: this.fromPoint.lng
        // },{
        //     latitude: this.$store.state.latitude,
        //     longitude: this.$store.state.longitude
        // }, this.railRadius, ()=>{
        //     // 在电子围栏半径内
        //     this.GetVin(way);
        // }, ()=>{
        //     console.log("在电子围栏外，无法取车");
        //     this.Toast({
        //         mask: true,
        //         message: '在电子围栏外，无法取车。'
        //     });
        // });
      },
      deleteImgDialog (index) {
        // 删除图片 打开
        this.deleteIndex = index;
        this.openAlert = true;
      },
      closeAlertDialog (state) {
        // 删除图片 关闭
        if(state === 'y'){
            this.src.splice(this.deleteIndex, 1);
            this.files.splice(this.deleteIndex, 1);
        }
        this.openAlert = false;
      },
      choiceAbType(item, index) {
        this.abnormalType = item.name;
        this.abnormalReas = "";
        this.open1 = false;
        this.abnormalReasArrX = this.abnormalReasArr[index];
      },
      choiceAbReas (item, index) {
        this.abnormalReas = item.name;
        this.open2 = false;
      },
      dones (mark) {
        /* 发送post请求 */
        let data = Object.assign({},this.$store.state.user,{
            content: {
                taskId: this.taskId
            }
        });
        // 提示
        this.Toast.loading({
            mask: true,
            message: '提交中...'
        });
        this.common.reqData(api.app('onroadWorked'), data, res=>{
            console.log(res.data);
            if(res.data.status == 100){
                this.Toast.success({
                    message: '提交成功'
                });
                if(mark == 'auto'){
                    this.common.tts("任务已自动完成。");
                }
                this.InitWebPage(res.data);
                // 提交成功后 全部制空
                this.vin = "";
                this.car = "";
                this.color = "";
                this.src = [];
                this.files = [];
                this.text = "";
                this.abnormalType = "";
                this.abnormalReas = "";
            }else{
                this.Toast({
                    message: res.data.msg
                });
            }
            this.isAction = true;
        },err =>{
            this.isAction = true;
            console.log(err)
        });
      },
      closeAlertDialog (f) {
        if(f == 'y'){
            this.dones();
        }
        this.openAlert = false;
      },
      submit () {
        this.common.distanceCompute({
            latitude: this.toPoint.lat,
            longitude: this.toPoint.lng
        },{
            latitude: this.$store.state.latitude,
            longitude: this.$store.state.longitude
        }, this.workRadius, ()=>{
            // 在电子围栏半径内
            this.dones();
        }, ()=>{
            this.openAlert = true;
        });
      },
      closeBottomSheet () {
        this.open = false;
      },
      openBotttomSheet (who) {
        who == 'open1' ? this.open1 = true : this.open2 = true;
      },
      onChange(picker, values) {
        picker.setColumnValues(1, citys[values[0]]);
      },
      paizhao(){
          let _this = this;
          if(window.plus){
            var cmr = plus.camera.getCamera();
            var res = cmr.supportedImageResolutions[0];
            var fmt = cmr.supportedImageFormats[0];
            console.log("Resolution: "+res+", Format: "+fmt);
            cmr.captureImage( function( path ){
                plus.io.resolveLocalFileSystemURL( path, function ( entry ) {
                    // 转化本地绝对路径
                    var url = plus.io.convertLocalFileSystemURL(path);
                    _this.src.push("file://"+url);
                    // 获取图片对象
                    entry.file( function(file){
                        var fileReader = new plus.io.FileReader();
                        fileReader.onloadend = function(evt) {
                            console.log(evt.target.result);
                            _this.files.push(evt.target.result);
                        }
                        fileReader.readAsDataURL(file);
                    });
                });
            },
            function( error ) {
                console.log( "拍照已经取消: " + error.message );
            },
            {resolution:res,format:fmt}
            );
          }
      },
      uploadSelf (flag, tts, opt) {
        /**
         * 0 偏移 1 超速 2 停留 
         */
        tts.length > 0 ? this.common.tts(tts) : '';
        let data = Object.assign({}, this.$store.state.user, {
            content: {
                flag: flag, // 标记
                taskId: this.taskId,
                accuracy: this.$store.state.accuracy, //精度
                speedXS: opt && opt.speed ? opt.speed : 0, // 限速
                py: opt && opt.py ? opt.py : 0,
                stayTime: this.stayTime, // 停留时间
                stayLoc: this.$store.state.addresses, // 位置
                lng: this.$store.state.longitude, 
                speed: Math.floor(this.$store.state.speed), // 超速速度
                lat: this.$store.state.latitude
            }
            //  img图片内容、停留时间stayTime、停留位置stayLoc、经度lng、纬度lat
        });
        this.common.reqData(api.app('onroadGetSpeed'), data, res=>{
            if(res.data.status == 100){
                console.log("已成功记录日志");
                if(flag == 1){
                    this.stayTime = 0;
                }
            }else{
                this.Toast({
                    message: res.data.msg
                });
            }
        },err =>{
            console.log(err)
        });
      },
      WatchingDiver () {
        // alert(this.watch);
        if (!this.watch) return false;
        // alert('开始监控');
        let pt = {
            lng: this.$store.state.longitude,
            lat: this.$store.state.latitude
        };

        let pointArr = [];
        this.trajectoryPlan.forEach((item, index) => {
            pointArr.push(item.point);
        });

        var h = [];
        for(var i=0; i < pointArr.length-1; i++){
            var a = pointArr[i], b = pointArr[i+1];
            /**
             * 求三角形的三边长
             */
            var x = this.common.GetTranslate(a, b);
            var y = this.common.GetTranslate(a, pt);
            var z = this.common.GetTranslate(pt, b);
            var f = x*x + y*y < z*z || x*x + z*z < y*y; // 判断线段为∠是否是钝角三角形
            
            /**
             * 根据海伦公式，算出三角形面积
             */
            var t = (x+y+z)/2;
            var s = Math.sqrt(t*(t-x)*(t-y)*(t-z));
            /**
             * 算出高度
             */
            var mh = 2 * s / x;

            var xs = 100000; // 倍数值

            x > 0 ? f ? h.push(Math.min(z, y) * xs) : h.push(mh * xs) : null;
        }

        console.log("当前点位", JSON.stringify(pt));
        console.log("司机到线段高集合：", JSON.stringify(h));
        console.log("最小值是：", Math.min.apply(null, h));
        console.log("当前最小值分段是：", this.common.GetIndex(h, Math.min.apply(null, h)));



        /**
         * 道路偏移
         */

        var spd = this.initSpeeds;
        if(this.trajectoryPlan && this.trajectoryPlan.length > 0){
            spd = this.trajectoryPlan[this.common.GetIndex(h, Math.min.apply(null, h))].speed;
        }
        console.log("初始化速度",spd);
        
        if (Math.min.apply(null, h) > this.distence && this.trajectoryPlan.length > 0) {
            if(((new Date()).getTime()) - this.preLeaveTime >= 20 * 1000){
                this.preLeaveTime = (new Date()).getTime();
                if(this.$store.state.accuracy > 0 && this.$store.state.accuracy <= this.accuracy && this.$store.state.accuracy){
                    this.uploadSelf(0, "偏移路段，" + (this.common.GetIndex(h, Math.min.apply(null, h)) + 1) + '，偏移值：' + Math.floor(Math.min.apply(null, h)), {
                        py: Math.floor(Math.min.apply(null, h)),
                        speed: null
                    });
                }
            }
        }
        
        /**
         * 超速
         */
        // 播报限速
        if(this.common.GetIndex(h, Math.min.apply(null, h)) !== this.CurrentSection || this.CurrentSection == 0){
            if(spd !== this.thePreSPD){
                this.common.tts("当前路段限速" + this.trajectoryPlan[this.common.GetIndex(h, Math.min.apply(null, h))].speed);
                this.CurrentSection = this.common.GetIndex(h, Math.min.apply(null, h)); // 当前路段
            }
            this.thePreSPD = spd;
        }

        if(Math.floor(this.$store.state.speed) > spd && spd !== 0){
            if(((new Date()).getTime()) - this.preSpeedingTime >= 20 * 1000){
                this.preSpeedingTime = (new Date()).getTime();
                if(this.$store.state.accuracy > 0 && this.$store.state.accuracy <= this.accuracy && this.$store.state.accuracy){
                    this.uploadSelf(1, '您已超速，当前速度：'+ Math.floor(this.$store.state.speed * this.overSpeed) + "。当前限速："+ spd, {
                        speed: spd,
                        py: null
                    });
                }
            }
        }

        /**
         * 停留开始
         */
        // if(!this.isBeginStay && this.$store.state.speed <= 2){
        //     console.log('---开始停留计时---');
        //     this.isBeginStay = true;
        //     this.stayIntalval = setInterval(() => {
        //         this.stayTime += 0.1;
        //     }, 100);
        // }

        // if(this.isBeginStay && this.$store.state.speed > 2){
        //     clearInterval(this.stayIntalval);
        //     if(this.stayTime > this.maxStayTime * 60){
        //         console.log('停留超过5分钟');
        //         this.uploadSelf(2, '你已经停留超过'+this.maxStayTime+'分钟');
        //     }
        // }

        this.common.distanceCompute({
            latitude: this.toPoint.lat,
            longitude: this.toPoint.lng
        },{
            latitude: this.$store.state.latitude,
            longitude: this.$store.state.longitude
        }, this.workRadius, ()=>{
            // 在电子围栏半径内
            if(this.isAction){
                this.isAction = false;
                this.dones('auto');
            }
        }, ()=>{
            console.log("在电子围栏外，无法完成。");
            // this.Toast({
            //     mask: true,
            //     message: '在电子围栏外，无法完成。'
            // });
        });
      },
      InitWebPage (data) {
        let flag = data.content.flag;
        this.FlagStatus = data.content.flag; 
        if(flag == 0){
            /**
             * vin
             */
            this.isShowVin = true;
            this.isShowSelect = false;
            this.isShowPaper = false;
            this.isShowToPlace = false;
            this.isShowChangeCar = false;
            this.isShowDone = false;
            this.watch = false;
            return false;
        }else if(flag == 1){
            /**
             * 目的地
             */
            this.isShowVin = false;
            this.isShowSelect = true;
            this.isShowPaper = true;
            this.isShowToPlace = true;
            this.isShowChangeCar = false;
            this.isShowDone = false;
        }else if(flag == 2){
            /**
             * 换车
             */
            this.isShowVin = false;
            this.isShowSelect = false;
            this.isShowPaper = true;
            this.isShowToPlace = false;
            this.isShowChangeCar = true;
            this.isShowDone = false;
        }else if(flag == 3){
            /**
             * 作业确认
             */
            this.isShowVin = false;
            this.isShowSelect = false;
            this.isShowPaper = true;
            this.isShowToPlace = false;
            this.isShowChangeCar = false;
            this.isShowDone = true;
        }
        this.itemCode = data.content.taskObject.itemCode ? data.content.taskObject.itemCode : '';
        this.overSpeed = data.content.taskObject.overSpeed ? data.content.taskObject.overSpeed : 0; // 速度系数
        this.accuracy = data.content.taskObject.accuracy ? data.content.taskObject.accuracy : 65; // 精度大小
        this.vehicleType = data.content.taskObject.vehicleType ? data.content.taskObject.vehicleType : '';
        this.color = data.content.taskObject.color ? data.content.taskObject.color : '';
        this.transportMode = data.content.taskObject.transportMode ? data.content.taskObject.transportMode : '';
        this.warehouse = data.content.taskObject.warehouse ? data.content.taskObject.warehouse : '';
        this.omDestLocGid = data.content.taskObject.omDestLocGid ? data.content.taskObject.omDestLocGid : '';
        this.vin = data.content.taskObject.vin ? data.content.taskObject.vin : '';
        this.taskId = data.content.taskObject.taskId ? data.content.taskObject.taskId : '';
        this.trajectoryPlan = data.content.trajectoryPlan ? data.content.trajectoryPlan : '';
        this.distence = data.content.taskObject.distence ? data.content.taskObject.distence : '';
        this.railRadius = data.content.taskObject.railRadius ? data.content.taskObject.railRadius : '';
        this.workRadius = data.content.taskObject.workRadius ? data.content.taskObject.workRadius : '';
        this.fromPoint = {
            lng: data.content.taskObject.longitude1 ? data.content.taskObject.longitude1 : 0,
            lat: data.content.taskObject.latitude1 ? data.content.taskObject.latitude1 : 0
        }
        this.toPoint = {
            lng: data.content.taskObject.longitude2 ? data.content.taskObject.longitude2 : 0,
            lat: data.content.taskObject.latitude2 ? data.content.taskObject.latitude2 : 0
        }
        this.endPoint = data.content.taskObject.endPoint ? data.content.taskObject.endPoint : '';
        this.initSpeeds = data.content.taskObject.speed ? data.content.taskObject.speed : 0;
        this.watch = data.content.watch ? data.content.watch : false;
        this.options = data.content.destination ? data.content.destination : [];
      },
      initDate(){
        this.common.reqData(api.app('onroadInit'), this.$store.state.user, res=>{
            console.log(res.data);
            if(res.data.status == 100){
                this.InitWebPage(res.data);
            }else{
                this.Toast({
                    message: res.data.msg
                });
            }
        },err =>{
            console.log(err)
        });
      }
  },
  mounted () {
    this.initDate();

    this.intervalInitData = setInterval(() => {
        // if(this.watch) {
        //     clearInterval(this.intervalInitData);
        // }else{
            this.initDate();
        // }
    }, 3000);


  },
  beforeCreate () {
  },
  beforeDestroy () {
    clearInterval(this.stayIntalval);
    clearInterval(this.intervalInitData);
  },
  computed: {
    latitudeChange () {
        return this.$store.state.latitude;
    },
    longitudeChange () {
        return this.$store.state.longitude;
    },
    speedChange () {
        return this.$store.state.speed;
    }
  },
  watch:{
    latitudeChange: function(data) {
        this.WatchingDiver();
    },
    longitudeChange: function(data) {
        this.WatchingDiver();
    },
    speedChange: function(data) {
        this.WatchingDiver();
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.mu-input{
    width: 85%;
    margin: 20px auto 0;
    display: block;
}
.imgs{
    width: 50px;
    height: 50px;
    overflow: hidden;
    margin: 10px;
}
.imgs img{
    width: 100%;
}
.photos{
    border: 1px solid #ccc;
    width: 90%;
    margin: 20px auto 0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}
i.iconfont.icon-icon25201{
    display: block;
    font-size: 50px;
    margin: 10px;
}
.paper{
    width: 90%;
    margin: 20px auto 0;
    padding: 10px 0;
}
.paper div{
    padding: 10px 20px;
}
.submit{
    display: block;
    width: 90%;
    margin: 20px auto;
}
.abnormal-box {
    width: 90%;
    margin: 0 auto;
    display: flex;
    justify-content: space-around;
}
.abnormal-box .mu-input{
    width: 45%;
}
em{padding: 0 2em;}
.mu-carousel{
    height: 100%;
}
#ylbox{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
#ylbox img{
    width: 100%;
    height: 100%;
}
header.mu-appbar{
    box-shadow: none;
    background: none;
    position: absolute;
    width: 100%;
}
</style>
